import { login, logout, getUserInfo } from "@/service/user";
import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { showToast, showFailToast } from "vant";

const getDefaultState = () => {
  return {
    token: getToken(), //刷新页面时，会从本地拿取token
    userInfo: {
      userEmail: "",
      userUid: "",
      orgCode: "",
      userName: "",
      mobilePhone: "",
    },
  };
};
export const useStore = defineStore("useStore", {
  state: getDefaultState,
  getters: {
    getUserInfo: (state) => state.userInfo,
  },
  actions: {
    // 登录
    login(userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password })
          .then((response) => {
            if (response.code == 0) {
              const { data } = response;
              this.token = data.token;
              setToken(data.token);
              showToast("登录成功！");
            } else {
              // showFailToast(response.msg);
            }
            resolve();
          })
          .catch((error) => {
            // showFailToast("系统错误！");
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo(this.token)
          .then((response) => {
            const { data } = response;
            if (!data) {
              return reject("Verification failed, please Login again.");
            }
            const { userEmail, userUid, orgCode, userName, mobilePhone } = data;
            this.userInfo = {
              userEmail,
              userUid,
              orgCode,
              userName,
              mobilePhone,
            };
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出
    logout() {
      return new Promise((resolve, reject) => {
        removeToken(); // must remove  token  first
        resetRouter();
        this.$reset();
        resolve();
        // logout(state.token)
        //   .then(() => {
        //     removeToken(); // must remove  token  first
        //     resetRouter();
        //     this.$reset();
        //     resolve();
        //   })
        //   .catch(error => {
        //     reject(error);
        //   });
      });
    },
    // 清除token
    resetToken() {
      return new Promise((resolve) => {
        removeToken(); // must remove  token  first
        this.$reset();
        resolve();
      });
    },
  },
});
